<template>
  <a-card :bordered="false">
    <a-row :gutter="8">
      <a-col :span="5">

        <div class="tree-wrapper">
          <a-input-search
                  v-model="queryParam.keywords"
                  @search="onSearch"
            placeholder="搜索关键字"
            style="width: 100%; margin-bottom: 1rem"
            />
          <a-menu
                  mode="inline" class="custom-tree"
          >
            <a-sub-menu v-for="cate in cateTree" v-if="cate.children">
                <span slot="title"><span>{{cate.title}}</span></span>
                <a-menu-item @click="handleCateClick" v-for="subcate in cate.children" :key="subcate.key"  >{{subcate.title}}</a-menu-item>
            </a-sub-menu>
            <a-menu-item @click="handleCateClick" v-else :key="subcate.key"  >{{cate.title}}</a-menu-item>
          </a-menu>
        </div>

      </a-col>
      <a-col :span="19">

        <div class="table-operator">
          <a-button type="primary" icon="plus" @click="handleAdd" >新建</a-button>
          <a-dropdown v-if="selectedRowKeys.length > 0">
            <a-menu slot="overlay">
              <a-menu-item @click="setAllStatus(1)" key="1">显示</a-menu-item>
              <a-menu-item @click="setAllStatus(2)" key="2">隐藏</a-menu-item>
            </a-menu>
            <a-button style="margin-left: 8px">
              批量操作 <a-icon type="down" />
            </a-button>
          </a-dropdown>
        </div>
        <s-table
          ref="table"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="false"
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >

        <span slot="status" slot-scope="text,record">
          <template >
            <a-badge status="success" v-if="record.status==1" text="显示" />
            <a-badge status="default" v-else text="隐藏" />
            </template>
        </span>

          <span slot="rank" slot-scope="text,record">
        <template >
        <editable-cell :text="text" @change="onRankChange(record.id, 'rank', $event)"/>
        </template>
      </span>

          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
            </template>
            <a-dropdown>
              <a class="ant-dropdown-link">
                更多 <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item >
                  <a-popconfirm title="删除后不可恢复,确定删除吗?" @confirm="onDelete(record)"  okText="确定" cancelText="取消">
                    <a href="javascript:;">删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>
        </s-table>
      </a-col>
    </a-row>


    <a-modal
            title="操作"
            :width="1000"
            style="top: 20px;"
            :bodyStyle="{maxHeight:'500px','overflowY':'scroll'}"
            v-model="visible"
            @ok="handleOk"
    >
      <a-spin :spinning="saveLoading">
        <a-form :form="form">

          <a-form-item
                  label="所属分类"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
          >
            <a-tree-select
                    v-decorator="[
                  'cate_id',
                  {rules: [{ required: true, message: '请输入选择分类' }]}
                ]"
                    style=" width: 90% ; margin-right: 10px; "
                    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                    :treeData="cateOptions"
                    allowClear
                    treeNodeFilterProp="title"
                    placeholder='请选择分类'
                    treeDefaultExpandAll
                    v-model="formData.cate_id"
            >
            </a-tree-select>
          </a-form-item>

          <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="标题"
                  hasFeedback
          >
            <a-input v-decorator="[
          'title',
          {rules: [{ required: true, message: '请输入文章标题' }]}
        ]"
                     placeholder="请输入文章标题"/>
          </a-form-item>

          <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="描述"
                  hasFeedback
          >
            <a-textarea autosize v-decorator="[
          'desc',
          {rules: []}
        ]"
                        placeholder="请输入描述"/>
          </a-form-item>

          <a-form-item
                  label="正文"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
          >

            <UEditor  style="width: 400px; height:520px;" :ueditorContent.sync="formData.content" ></UEditor>
          </a-form-item>



          <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="状态"
                  hasFeedback
          >
            <r-switch  :formData="formData" field="status" :checkedValue="1" :unCheckedValue="2"  checkedChildren="显示" unCheckedChildren="隐藏" />
          </a-form-item>

        </a-form>

      </a-spin>
      <template slot="footer">
        <a-button key="cancel" @click="handleCancel">取消</a-button>
        <a-button key="forward" :loading="saveLoading" type="primary" @click="handleOk">保存</a-button>
      </template>
    </a-modal>

  </a-card>


</template>

<script>
import STable from '@/components/table/'
import UEditor from '@/components/UEditor/'
import EditableCell from '@/components/EditableCell/'
import RSwitch from '@/components/RSwitch/'
import PicUploader from '@/components/PicUploader/'
import moment from 'moment'
import { getCateTreeList, getContentList,editContent,addContent,getContentDetail ,setContentRank,deleteContent,setContentAllStatus } from '@/api/cms'

export default {
  name: 'ContentList',
  components: {
    STable,
    EditableCell,
    RSwitch,
    PicUploader,
    UEditor,
  },
  data () {
    return {
      visible: false,
      saveLoading: false,
      openKeys: [ ],
      // 查询参数
      queryParam: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      form: this.$form.createForm(this),
      mdl: {},
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: 'id'
        },
        {
          title: '标题',
          dataIndex: 'title'
        },
        {
          title: '排序',
          dataIndex: 'rank',
          scopedSlots: { customRender: 'rank' },
        },
        {
          title: '状态',
          dataIndex: 'status',
          filters: [
            {
              text: '显示',
              value: '1'
            },
            {
              text: '隐藏',
              value: '2'
            }],
          filterMultiple: false,
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '更新时间',
          dataIndex: 'update_time',
          customRender: (text) =>  {
            return moment(text*1000).format('YYYY-MM-DD HH:mm:ss');
          }
        },
        {
          table: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData');
        console.log(this.queryParam);
        this.queryParam.status = 0;
        if(parameter.status && parameter.status.length){
          this.queryParam.status =  parameter.status[0];
        }
        this.queryParam = Object.assign(parameter, this.queryParam);

        return getContentList(this.queryParam)
          .then(res => {
            return res.data
          })
          
      },
      cateTree: [],
      cateOptions: [],
      selectedRowKeys: [],
      selectedRows: [],
      formData : {
        id:0,
        title: '',
        cate_ids:[],
        cate_id:'',
        desc: '',
        pic: [],
        pics: [],
        content:'',
        rank:0,
        status: 1
      }
    }
  },
  created () {
    getCateTreeList().then(res => {
      console.log('getCateTreeList',res);
      this.cateTree = res.data
      this.cateOptions = res.data
    })
  },
  methods: {
    handleCancel(){
      this.visible = false
    },
    // 增
    handleAdd() {
      let that = this;
      this.visible = true;
      this.form.resetFields();
      this.formData = {
        id:0,
        cate_ids:[],
        cate_id:'',
        title: '',
        desc: '',
        pic: [],
        pics: [],
        content:'',
        rank:0,
        status: 1
      };
      setTimeout( () =>{
        that.form.setFieldsValue({ ...this.formData });
      });
    },
    // 改
    handleEdit(record) {
      let self = this
      getContentDetail({ id: record.id }).then(res => {
        setTimeout(()=>{
          res.data.cate_id = res.data.cate_id+'';
          self.form.setFieldsValue({ ...res.data })
        },1)
//          self.formData = {...res.data};
        self.formData = Object.assign(self.formData, res.data) //尼玛 日期选择器有bug 必须这样赋值
        self.formData.id = res.data.id;
      })
      this.visible = true
    },

    // 增改 处理
    handleOk(e) {
      let self = this;
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          console.log('Received valuess of formData: ', self.formData)
          self.saveLoading = true;
          let formData = {
            id:self.formData.id,
            title: values.title,
            cate_id: values.cate_id,
            desc: values.desc,
            pic:self.formData.pic,
            pics:self.formData.pics,
            content:self.formData.content,
            status:self.formData.status,
          };
          if(self.formData.id) {
            editContent(formData).then(res => {
              self.$message.success('修改成功')
              self.$refs.table.refresh(true)
              self.visible = false;
              self.saveLoading = false;
            }).catch(err =>{
              self.$message.error(err.data.msg);
              self.saveLoading = false;
            })
          }else{
            addContent(formData).then(res => {
              self.$message.success('新增成功')
              self.$refs.table.refresh(true)
              self.visible = false
              self.saveLoading = false;
            }).catch(err =>{
              self.$message.error(err.data.msg);
              self.saveLoading = false;
            })
          }
        }
      })
    },

    onDelete(record) {
      let self = this
      deleteContent({ id: record.id }).then(res => {
        self.$message.success('删除成功')
        self.$refs.table.refresh(true)
      }).catch(err =>{
        self.$message.error(err.data.msg)
      })
    }
      ,
    // 查
    onSearch() {
      let self = this;
      self.$refs.table.refresh(true)
    },
    handleCateClick(e){
      let self = this;
      self.queryParam.cate_id = e.key;
      self.$refs.table.refresh(true)
    },

    setAllStatus(status){
      let self = this;
      setContentAllStatus({
        ids:self.selectedRowKeys,
        status:status,
      })
              .then(res => {
                self.$message.success('设置成功')
                self.$refs.table.refresh(true)
              })
    },

    onRankChange(key, dataIndex, value) {
      let self = this;
      setContentRank({
        id: key,
        rank:value
      }).then(res => {
        self.$refs.table.refresh(true)
      }).catch(err =>{
        self.$message.error(err.data.msg)
      })
    },

    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
  }
}
</script>

<style lang="less">
  .custom-tree {

    /deep/ .ant-menu-item-group-title {
      position: relative;
      &:hover {
        .btn {
          display: block;
        }
      }
    }

    /deep/ .ant-menu-item {
      &:hover {
        .btn {
          display: block;
        }
      }
    }

    /deep/ .btn {
      display: none;
      position: absolute;
      top: 0;
      right: 10px;
      width: 20px;
      height: 40px;
      line-height: 40px;
      z-index: 1050;

      &:hover {
        transform: scale(1.2);
        transition: 0.5s all;
      }
    }
  }
</style>